<template>
  <div class="interactive-erase">
    <!-- 顶部标题和指引区 -->
    <div class="page-header">
      <div class="header-content">
        <h1>{{ $t('InteractiveErase.Title') }}</h1>
        <p>{{ $t('InteractiveErase.Subtitle') }}</p>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧区域：包含工具栏和画布 -->
      <div class="editor-area">
        <!-- 顶部工具栏 -->
        <div class="toolbar">
          <div class="left-tools">
            <el-button @click="handleOpenUpload" :disabled="processing">
              <el-icon><Upload /></el-icon> {{ $t('InteractiveErase.UploadButton') }}
            </el-button>
            <div class="divider"></div>
            
            <!-- 编辑模式切换 -->
            <el-radio-group v-model="mode" class="mode-selector" :disabled="!currentImage || processing">
              <el-radio-button value="box">
                <el-icon><Crop /></el-icon> {{ $t('InteractiveErase.EditModes.Box') }}
              </el-radio-button>
              <el-radio-button value="brush">
                <el-icon><Brush /></el-icon> {{ $t('InteractiveErase.EditModes.Brush') }}
              </el-radio-button>
            </el-radio-group>
            
            <!-- 笔刷大小控制 -->
            <div class="brush-size-control" v-if="mode === 'brush'">
              <el-popover placement="bottom" :width="200" trigger="click">
                <template #reference>
                  <el-button class="brush-btn" :disabled="!currentImage || processing">
                    <div class="brush-preview" :style="{width: brushSize/2 + 'px', height: brushSize/2 + 'px'}"></div>
                    {{ $t('InteractiveErase.BrushSize') }}
                  </el-button>
                </template>
                <el-slider 
                  v-model="brushSize" 
                  :min="5" 
                  :max="50" 
                  :step="1"
                  show-input
                />
              </el-popover>
            </div>
          </div>
          
          <div class="right-tools">
            <el-tooltip :content="$t('InteractiveErase.TextModeTooltip')" placement="top" v-if="currentImage">
              <el-switch 
                v-model="isTextMode" 
                :active-text="$t('InteractiveErase.TextMode')" 
                :inactive-text="$t('InteractiveErase.ImageMode')"
                :disabled="processing"
              />
            </el-tooltip>
            
            <el-button @click="undoLastAction" :disabled="!currentImage || drawHistory.length === 0 || processing">
              <el-icon><Back /></el-icon> {{ $t('InteractiveErase.UndoButton') }}
            </el-button>
            
            <el-button @click="resetImage" :disabled="!currentImage || processing">
              <el-icon><RefreshRight /></el-icon> {{ $t('InteractiveErase.ResetButton') }}
            </el-button>
            
            <el-button 
              type="primary" 
              @click="applyErase" 
              :loading="processing"
              :disabled="!currentImage || drawHistory.length === 0"
            >
              <el-icon><Edit /></el-icon> {{ $t('InteractiveErase.EraseButton') }}
            </el-button>

            <!-- 下载按钮 -->
            <el-button 
              type="success" 
              @click="downloadResult" 
              v-if="resultImage"
              :disabled="processing"
            >
              <el-icon><Download /></el-icon> {{ $t('InteractiveErase.DownloadButton') }}
            </el-button>
          </div>
        </div>
        
        <!-- 画布区域 -->
        <div class="canvas-workspace">
          <!-- 左侧：原图编辑区域 -->
          <div class="workspace-left">
            <div class="canvas-container" v-if="currentImage" ref="canvasContainer">
              <div class="canvas-wrapper" :style="{transform: `scale(${zoom})`}" :class="{'has-image': currentImage}">
                <canvas 
                  ref="imageCanvas" 
                  @mousedown="startDraw" 
                  @mousemove="drawing" 
                  @mouseup="endDraw"
                  @mouseleave="endDraw"
                  class="main-canvas"
                ></canvas>
                <canvas 
                  ref="overlayCanvas" 
                  class="overlay-canvas"
                  @mousedown="startDraw" 
                  @mousemove="drawing" 
                  @mouseup="endDraw"
                  @mouseleave="endDraw"
                ></canvas>
              </div>
            </div>
            
            <div class="upload-area" v-if="!currentImage">
              <div class="upload-box" @click="handleOpenUpload">
                <div class="upload-icon">
                  <el-icon :size="48"><Upload /></el-icon>
                </div>
                <div class="upload-text">{{ $t('InteractiveErase.UploadText') }}</div>
                <div class="upload-tip">{{ $t('InteractiveErase.UploadTip') }}</div>
              </div>
            </div>
            
            <div class="canvas-controls" v-if="currentImage">
              <div class="zoom-controls">
                <el-button @click="adjustZoom(-0.1)" :disabled="zoom <= 0.5">
                  <el-icon><ZoomOut /></el-icon>
                </el-button>
                <span class="zoom-value">{{ Math.round(zoom * 100) }}%</span>
                <el-button @click="adjustZoom(0.1)" :disabled="zoom >= 2">
                  <el-icon><ZoomIn /></el-icon>
                </el-button>
              </div>
              
              <div class="action-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>{{ mode === 'box' ? $t('InteractiveErase.ActionTips.Box') : $t('InteractiveErase.ActionTips.Brush') }}</span>
              </div>
            </div>
          </div>
          
          <!-- 右侧：结果展示区域 -->
          <div class="workspace-right">
            <div class="result-container">
              <img v-if="resultImage" :src="resultImage" alt="处理结果" />
              <div v-else class="no-result">
                {{ $t('InteractiveErase.ResultText') }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <input 
      type="file" 
      ref="fileInput" 
      style="display: none" 
      accept="image/*"
      @change="handleFileSelected"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { 
  Crop, Brush, ZoomIn, ZoomOut, Delete, RefreshRight, 
  Back, Edit, Download, InfoFilled, Upload
} from '@element-plus/icons-vue'
import { eraseWithBox, eraseWithMask } from '@/api/eraser/index'

// 初始化国际化
const { t } = useI18n()

// 响应式状态
const currentImage = ref(null) // 当前图片URL
const resultImage = ref(null) // 处理结果图片URL
const fileInput = ref(null) // 文件输入元素
const imageCanvas = ref(null) // 主画布
const overlayCanvas = ref(null) // 叠加层画布
const canvasContainer = ref(null) // 画布容器
const originalImageObj = ref(null) // 原始图片对象
const comparisonSlider = ref(null) // 对比滑块

// 编辑状态
const mode = ref('box') // 编辑模式: box/brush
const brushSize = ref(20) // 笔刷大小
const isTextMode = ref(true) // 文本模式/图像模式
const isDrawing = ref(false) // 是否正在绘制
const startPos = ref({ x: 0, y: 0 }) // 起始位置
const drawHistory = ref([]) // 绘制历史
const selectedHistoryIndex = ref(-1) // 选中的历史索引
const zoom = ref(1) // 缩放比例
const processing = ref(false) // 处理中状态
const showResult = ref(false) // 显示结果弹窗
const sliderPosition = ref(50) // 结果对比滑块位置
const isDraggingSlider = ref(false) // 是否正在拖动滑块

// 画布上下文
const ctx = reactive({
  main: null, // 主画布上下文
  overlay: null // 叠加层画布上下文
})

// 图片原始尺寸
const imageSize = reactive({
  width: 0,
  height: 0
})

// 打开文件选择
const handleOpenUpload = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 处理文件选择
const handleFileSelected = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error(t('InteractiveErase.Messages.InvalidFile'))
    return
  }
  
  // 重置状态
  resetState()
  
  // 创建预览URL并设置图片
  const reader = new FileReader()
  reader.onload = (e) => {
    // 先清空当前图片
    currentImage.value = null
    
    // 创建图像对象
    const img = new Image()
    img.onload = () => {
      // 保存图片尺寸
      imageSize.width = img.width
      imageSize.height = img.height
      originalImageObj.value = img
      
      // 设置当前图片
      currentImage.value = e.target.result
      
      // 加载到画布
      nextTick(() => {
        initCanvas()
      })
    }
    img.src = e.target.result
  }
  reader.readAsDataURL(file)
  
  // 重置文件输入，允许重新选择相同文件
  event.target.value = ''
}

// 获取鼠标在画布上的实际坐标
const getCanvasCoordinates = (e, canvas) => {
  const rect = canvas.getBoundingClientRect()
  const scaleX = canvas.width / rect.width
  const scaleY = canvas.height / rect.height
  
  return {
    x: (e.clientX - rect.left) * scaleX,
    y: (e.clientY - rect.top) * scaleY
  }
}

// 初始化画布
const initCanvas = () => {
  if (!imageCanvas.value || !overlayCanvas.value || !canvasContainer.value || !originalImageObj.value) {
    console.error('初始化失败: 缺少必要组件')
    return
  }
  
  try {
    // 设置画布尺寸为图像原始尺寸
    const canvas_width = imageSize.width
    const canvas_height = imageSize.height
    
    // 设置画布尺寸
    imageCanvas.value.width = canvas_width
    imageCanvas.value.height = canvas_height
    overlayCanvas.value.width = canvas_width
    overlayCanvas.value.height = canvas_height
    
    // 获取画布上下文
    ctx.main = imageCanvas.value.getContext('2d')
    ctx.overlay = overlayCanvas.value.getContext('2d')
    
    if (!ctx.main || !ctx.overlay) {
      console.error('初始化失败: 无法获取画布上下文')
      return
    }
    
    // 清除画布
    ctx.main.clearRect(0, 0, canvas_width, canvas_height)
    ctx.overlay.clearRect(0, 0, canvas_width, canvas_height)
    
    // 直接绘制图像
    ctx.main.drawImage(originalImageObj.value, 0, 0, canvas_width, canvas_height)
    
    // 设置画布容器尺寸
    const canvasWrapper = imageCanvas.value.parentElement
    if (canvasWrapper) {
      const containerWidth = canvasContainer.value.clientWidth - 32
      const containerHeight = canvasContainer.value.clientHeight - 32
      
      // 计算适合容器的尺寸
      const scale = Math.min(
        containerWidth / canvas_width,
        containerHeight / canvas_height
      )
      
      const displayWidth = canvas_width * scale
      const displayHeight = canvas_height * scale
      
      canvasWrapper.style.width = `${displayWidth}px`
      canvasWrapper.style.height = `${displayHeight}px`
    }
    
    // 重置缩放
    zoom.value = 1
    
  } catch (error) {
    console.error('画布初始化发生错误:', error)
    ElMessage.error(t('InteractiveErase.Messages.InitFailed'))
  }
}

// 调整缩放
const adjustZoom = (delta) => {
  const newZoom = zoom.value + delta
  if (newZoom >= 0.5 && newZoom <= 2) {
    zoom.value = newZoom
    
    // 当缩放改变时，调整画布容器大小
    nextTick(() => {
      const canvasWrapper = imageCanvas.value?.parentElement
      if (canvasWrapper) {
        const originalWidth = parseFloat(canvasWrapper.style.width || '0')
        const originalHeight = parseFloat(canvasWrapper.style.height || '0')
        
        if (originalWidth > 0 && originalHeight > 0) {
          canvasWrapper.style.width = `${originalWidth}px`
          canvasWrapper.style.height = `${originalHeight}px`
        }
      }
    })
  }
}

// 开始绘制
const startDraw = (e) => {
  if (!ctx.overlay || processing.value) return
  
  isDrawing.value = true
  const pos = getCanvasCoordinates(e, overlayCanvas.value)
  startPos.value = pos
  
  if (mode.value === 'brush') {
    ctx.overlay.beginPath()
    ctx.overlay.fillStyle = 'rgba(255, 255, 255, 0.8)'
    ctx.overlay.arc(pos.x, pos.y, brushSize.value / 2, 0, Math.PI * 2)
    ctx.overlay.fill()
  }
}

// 绘制过程
const drawing = (e) => {
  if (!isDrawing.value || !ctx.overlay) return
  
  const currentPos = getCanvasCoordinates(e, overlayCanvas.value)
  
  if (mode.value === 'box') {
    // 清除当前绘制
    ctx.overlay.clearRect(0, 0, overlayCanvas.value.width, overlayCanvas.value.height)
    
    // 绘制矩形
    const width = currentPos.x - startPos.value.x
    const height = currentPos.y - startPos.value.y
    
    ctx.overlay.beginPath()
    ctx.overlay.rect(
      startPos.value.x,
      startPos.value.y,
      width,
      height
    )
    ctx.overlay.strokeStyle = 'red'
    ctx.overlay.lineWidth = 2
    ctx.overlay.stroke()
    ctx.overlay.fillStyle = 'rgba(255, 0, 0, 0.2)'
    ctx.overlay.fill()
  } else if (mode.value === 'brush') {
    // 绘制笔刷
    const lastPos = startPos.value
    
    ctx.overlay.beginPath()
    ctx.overlay.moveTo(lastPos.x, lastPos.y)
    ctx.overlay.lineTo(currentPos.x, currentPos.y)
    ctx.overlay.lineWidth = brushSize.value
    ctx.overlay.strokeStyle = 'rgba(255, 255, 255, 0.8)'
    ctx.overlay.lineCap = 'round'
    ctx.overlay.lineJoin = 'round'
    ctx.overlay.stroke()
    
    // 在当前位置绘制圆形，使笔触更平滑
    ctx.overlay.beginPath()
    ctx.overlay.arc(currentPos.x, currentPos.y, brushSize.value / 2, 0, Math.PI * 2)
    ctx.overlay.fillStyle = 'rgba(255, 255, 255, 0.8)'
    ctx.overlay.fill()
    
    // 更新起始位置
    startPos.value = currentPos
  }
}

// 结束绘制
const endDraw = (e) => {
  if (!isDrawing.value || !ctx.overlay) return
  
  const endPos = getCanvasCoordinates(e, overlayCanvas.value)
  
  if (mode.value === 'box') {
    // 保存当前框选区域
    const width = overlayCanvas.value.width
    const height = overlayCanvas.value.height
    
    // 确保坐标在0-1范围内
    const startX = Math.max(0, Math.min(startPos.value.x, endPos.x)) / width
    const startY = Math.max(0, Math.min(startPos.value.y, endPos.y)) / height
    const endX = Math.max(0, Math.min(Math.max(startPos.value.x, endPos.x), width)) / width
    const endY = Math.max(0, Math.min(Math.max(startPos.value.y, endPos.y), height)) / height
    
    drawHistory.value = [{
      type: 'box',
      startX: startX,
      startY: startY,
      endX: endX,
      endY: endY,
      width: width,
      height: height
    }]
  } else if (mode.value === 'brush') {
    // 保存当前涂抹内容
    const tempCanvas = document.createElement('canvas')
    tempCanvas.width = overlayCanvas.value.width
    tempCanvas.height = overlayCanvas.value.height
    const tempCtx = tempCanvas.getContext('2d')
    tempCtx.drawImage(overlayCanvas.value, 0, 0)
    
    drawHistory.value = [{
      type: 'brush',
      maskData: tempCanvas.toDataURL('image/png'),
      size: { width: overlayCanvas.value.width, height: overlayCanvas.value.height }
    }]
  }
  
  isDrawing.value = false
}

// 重绘历史操作
const redrawHistory = () => {
  if (!ctx.overlay) return
  
  ctx.overlay.clearRect(0, 0, overlayCanvas.value.width, overlayCanvas.value.height)
  
  // 只绘制最后一个操作
  const lastOperation = drawHistory.value[0]
  if (!lastOperation) return
  
  if (lastOperation.type === 'box') {
    ctx.overlay.beginPath()
    ctx.overlay.rect(
      lastOperation.startX,
      lastOperation.startY,
      lastOperation.endX - lastOperation.startX,
      lastOperation.endY - lastOperation.startY
    )
    ctx.overlay.strokeStyle = 'red'
    ctx.overlay.lineWidth = 2
    ctx.overlay.stroke()
    ctx.overlay.fillStyle = 'rgba(255, 0, 0, 0.2)'
    ctx.overlay.fill()
  } else if (lastOperation.type === 'brush') {
    const img = new Image()
    img.onload = () => {
      ctx.overlay.globalAlpha = 0.3
      ctx.overlay.drawImage(img, 0, 0)
      ctx.overlay.globalAlpha = 1.0
    }
    img.src = lastOperation.maskData
  }
}

// 撤销上一步操作
const undoLastAction = () => {
  drawHistory.value = []
  
  if (ctx.overlay) {
    ctx.overlay.clearRect(0, 0, overlayCanvas.value.width, overlayCanvas.value.height)
  }
  
  ElMessage.info(t('InteractiveErase.Messages.UndoSuccess'))
}

// 重置图片
const resetImage = () => {
  resetState()
  resultImage.value = null
  
  if (currentImage.value && originalImageObj.value) {
    initCanvas()
  }
  
  ElMessage.success(t('InteractiveErase.Messages.ResetSuccess'))
}

// 重置状态
const resetState = () => {
  drawHistory.value = []
  selectedHistoryIndex.value = -1
  
  if (ctx.overlay) {
    ctx.overlay.clearRect(0, 0, overlayCanvas.value.width, overlayCanvas.value.height)
  }
}

// 应用擦除
const applyErase = async () => {
  if (!currentImage.value || drawHistory.value.length === 0) return
  
  processing.value = true
  const loadingInstance = ElLoading.service({
    lock: true,
    text: t('InteractiveErase.Loading.Processing'),
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    // 准备请求数据
    const imageBase64 = currentImage.value.split(',')[1] // 去除Data URL前缀
    
    let response
    
    if (mode.value === 'box') {
      // 框选模式
      const boxItem = drawHistory.value[0]
      
      // 确保所有坐标都是有效的数字
      if (!boxItem || typeof boxItem.startX !== 'number' || typeof boxItem.startY !== 'number' ||
          typeof boxItem.endX !== 'number' || typeof boxItem.endY !== 'number') {
        throw new Error(t('InteractiveErase.Messages.InvalidBox'))
      }
      
      const coordinates = [[
        [boxItem.startX, boxItem.startY],
        [boxItem.endX, boxItem.startY],
        [boxItem.endX, boxItem.endY],
        [boxItem.startX, boxItem.endY]
      ]]
      
      // 调用框选接口
      response = await eraseWithBox(imageBase64, coordinates, isTextMode.value)
    } else {
      // 笔刷模式 - 生成遮罩图
      const maskCanvas = document.createElement('canvas')
      maskCanvas.width = imageSize.width
      maskCanvas.height = imageSize.height
      const maskCtx = maskCanvas.getContext('2d')
      
      // 设置遮罩图背景为黑色（表示透明区域）
      maskCtx.fillStyle = 'black'
      maskCtx.fillRect(0, 0, maskCanvas.width, maskCanvas.height)
      
      // 将涂抹区域绘制为白色
      maskCtx.fillStyle = 'white'
      maskCtx.drawImage(overlayCanvas.value, 0, 0)
      
      // 获取遮罩图的base64
      const maskBase64 = maskCanvas.toDataURL('image/png').split(',')[1]
      
      try {
        // 调用涂抹接口
        response = await eraseWithMask(imageBase64, maskBase64)
      } catch (error) {
        console.error('API调用失败:', error)
        throw new Error(t('InteractiveErase.Messages.ApiError'))
      }
    }
    
    // 处理响应
    if (response?.code === 200) {
      const result = response.data
      if (result?.parameter?.has_watermark) {
        // 设置结果图片URL
        resultImage.value = result.media_info_list[0].media_data
        ElMessage.success(t('InteractiveErase.Messages.EraseSuccess'))
      } else {
        resultImage.value = null
        ElMessage.warning(t('InteractiveErase.Messages.NoWatermark'))
      }
    } else {
      throw new Error(response?.msg || t('InteractiveErase.Messages.ProcessFailed'))
    }
  } catch (error) {
    console.error('水印擦除失败:', error)
    ElMessage.error(error.message || t('InteractiveErase.Messages.ProcessFailed'))
    resultImage.value = null
  } finally {
    processing.value = false
    loadingInstance.close()
  }
}

// 下载结果
const downloadResult = async () => {
  if (!resultImage.value) {
    ElMessage.warning(t('InteractiveErase.Messages.NoDownloadable'))
    return
  }

  let loadingInstance = null
  try {
    // 显示加载提示
    loadingInstance = ElLoading.service({
      lock: true,
      text: t('InteractiveErase.Loading.Downloading'),
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 下载图片
    const response = await fetch(resultImage.value)
    const blob = await response.blob()
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 设置文件名
    const extension = resultImage.value.split('.').pop()?.toLowerCase() || 'png'
    link.download = `watermark_removed_${new Date().getTime()}.${extension}`
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    // 关闭加载提示
    if (loadingInstance) {
      loadingInstance.close()
      loadingInstance = null
    }
    
    ElMessage.success(t('InteractiveErase.Messages.DownloadSuccess'))
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error(t('InteractiveErase.Messages.DownloadFailed'))
  } finally {
    // 确保加载提示被关闭
    if (loadingInstance) {
      loadingInstance.close()
    }
  }
}

// 滑块拖动相关
const startSliderDrag = (e) => {
  isDraggingSlider.value = true
  document.addEventListener('mousemove', moveSlider)
  document.addEventListener('mouseup', endSliderDrag)
  e.preventDefault()
}

const moveSlider = (e) => {
  if (!isDraggingSlider.value || !comparisonSlider.value) return
  
  const sliderRect = comparisonSlider.value.getBoundingClientRect()
  const newPosition = ((e.clientX - sliderRect.left) / sliderRect.width) * 100
  
  // 限制范围在0-100之间
  sliderPosition.value = Math.max(0, Math.min(100, newPosition))
}

const endSliderDrag = () => {
  isDraggingSlider.value = false
  document.removeEventListener('mousemove', moveSlider)
  document.removeEventListener('mouseup', endSliderDrag)
}

// 监听窗口大小变化
onMounted(() => {
  window.addEventListener('resize', () => {
    if (currentImage.value) {
      nextTick(() => {
        initCanvas()
      })
    }
  })
})

// 在组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', initCanvas)
  document.removeEventListener('mousemove', moveSlider)
  document.removeEventListener('mouseup', endSliderDrag)
})

// 监听模式变化
watch(mode, (newMode) => {
  // 切换模式时清除所有绘制
  drawHistory.value = []
  if (ctx.overlay) {
    ctx.overlay.clearRect(0, 0, overlayCanvas.value.width, overlayCanvas.value.height)
  }
  const modeName = newMode === 'box' ? t('InteractiveErase.EditModes.Box') : t('InteractiveErase.EditModes.Brush')
  ElMessage.info(t('InteractiveErase.Messages.ModeChanged', { mode: modeName }))
})
</script>

<style lang="scss" scoped>
.interactive-erase {
  width: 100%;
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.page-header {
  background-color: #fff;
  padding: 8px 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.main-content {
  flex: 1;
  padding: 12px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 1440px;
  margin: 0 auto;
  width: 100%;
  min-height: 0;
  overflow: hidden;
}

.editor-area {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  max-height: 900px;
}

.toolbar {
  padding: 12px 16px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  flex-wrap: nowrap;
}

.left-tools {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: nowrap;
}

.right-tools {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: nowrap;
}

.canvas-workspace {
  flex: 1;
  display: flex;
  min-height: 0;
  overflow: hidden;
  background-color: #f0f0f0;
  background-image: linear-gradient(45deg, #ddd 25%, transparent 25%), 
                    linear-gradient(-45deg, #ddd 25%, transparent 25%), 
                    linear-gradient(45deg, transparent 75%, #ddd 75%), 
                    linear-gradient(-45deg, transparent 75%, #ddd 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
}

.workspace-left,
.workspace-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  box-sizing: border-box;
  min-width: 0;
  position: relative;
  justify-content: center;
}

.canvas-container,
.result-container {
  flex: 1;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  background: transparent;
  border-radius: 8px;
  overflow: auto;
  cursor: move;
  max-height: calc(100vh - 280px);
}

.canvas-wrapper {
  position: relative;
  transform-origin: center;
  transition: transform 0.1s ease;
  display: inline-block;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  &.has-image {
    display: inline-block;
    background: #fff;
  }
}

.main-canvas,
.overlay-canvas {
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  width: 100%;
  height: 100%;
  cursor: crosshair;
}

.main-canvas {
  z-index: 1;
}

.overlay-canvas {
  z-index: 2;
  pointer-events: none;
}

.result-container {
  background: transparent;
  cursor: default;
  
  img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .no-result {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    color: #909399;
    font-size: 14px;
    text-align: center;
  }
}

.upload-area {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;
  background: transparent;
}

.upload-box {
  width: 320px;
  height: 320px;
  border: 2px dashed #409eff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: rgba(255, 255, 255, 0.95);
  gap: 12px;
  
  &:hover {
    border-color: #409eff;
    background-color: rgba(255, 255, 255, 1);
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .upload-icon {
    font-size: 48px;
    color: #409eff;
    margin-bottom: 8px;
  }

  .upload-text {
    font-size: 18px;
    color: #303133;
    font-weight: 500;
    margin-bottom: 4px;
  }

  .upload-tip {
    font-size: 14px;
    color: #909399;
  }
}

.canvas-controls {
  margin-top: 12px;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: absolute;
  bottom: 16px;
  left: 16px;
  right: 16px;
  z-index: 10;
}

.zoom-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .zoom-value {
    min-width: 50px;
    text-align: center;
    font-size: 14px;
    color: #606266;
  }
}

.action-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 13px;
  
  .el-icon {
    color: #409eff;
  }
}

// 结果比较样式
.result-dialog {
  .el-dialog__body {
    padding: 0;
  }
  
  .result-header {
    padding: 20px;
    text-align: center;
    background-color: #f5f7fa;
    
    h3 {
      margin: 0;
      color: #303133;
      font-size: 20px;
    }
    
    p {
      margin: 8px 0 0;
      color: #909399;
      font-size: 14px;
    }
  }
}

.result-comparison {
  position: relative;
  height: calc(100vh - 240px);
  overflow: hidden;
}

.comparison-slider {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  cursor: col-resize;
  
  .before-image, .after-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;
  }
  
  .after-image {
    border-right: 2px solid #fff;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.5);
    overflow: hidden;
  }
  
  .slider-handle {
    position: absolute;
    top: 0;
    width: 2px;
    height: 100%;
    background-color: #fff;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.5);
    cursor: col-resize;
    
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: #fff;
      box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 2;
    }
  }
}

.comparison-labels {
  position: absolute;
  bottom: 20px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  box-sizing: border-box;
  
  span {
    background-color: rgba(0, 0, 0, 0.7);
    color: #fff;
    font-size: 14px;
    padding: 6px 12px;
    border-radius: 4px;
  }
}

.dialog-footer {
  padding: 16px 20px;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background-color: #fff;
}

// 移动端适配
@media (max-width: 768px) {
  .toolbar {
    padding: 8px;
    flex-direction: column;
    gap: 8px;
    
    .left-tools, .right-tools {
      width: 100%;
      flex-wrap: wrap;
      gap: 8px;
    }
  }
  
  .canvas-controls {
    flex-direction: column;
    gap: 8px;
    padding: 8px;
  }
  
  .action-tip {
    text-align: center;
    width: 100%;
  }
}

// 移除底部的 DevTools 提示样式
:deep(.dev-tools-notice) {
  display: none !important;
}
</style>